Index: lib/libutil/pty.c
===================================================================
RCS file: /home/ncvs/src/lib/libutil/pty.c,v
retrieving revision 1.15
diff -u -I__FBSDID -I$FreeBSD -r1.15 pty.c
--- lib/libutil/pty.c	18 Oct 2003 10:04:16 -0000	1.15
+++ lib/libutil/pty.c	10 Jan 2008 20:50:22 -0000
@@ -54,50 +54,55 @@
 #include <unistd.h>
 
 int
-openpty(int *amaster, int *aslave, char *name, struct termios *termp, struct winsize *winp)
+openpty(int *amaster, int *aslave, char *name, struct termios *termp,
+    struct winsize *winp)
 {
-	char line[] = "/dev/ptyXX";
-	const char *cp1, *cp2;
-	int master, slave, ttygid;
-	struct group *gr;
-
-	if ((gr = getgrnam("tty")) != NULL)
-		ttygid = gr->gr_gid;
-	else
-		ttygid = -1;
-
-	for (cp1 = "pqrsPQRS"; *cp1; cp1++) {
-		line[8] = *cp1;
-		for (cp2 = "0123456789abcdefghijklmnopqrstuv"; *cp2; cp2++) {
-			line[5] = 'p';
-			line[9] = *cp2;
-			if ((master = open(line, O_RDWR, 0)) == -1) {
-				if (errno == ENOENT)
-					break; /* try the next pty group */
-			} else {
-				line[5] = 't';
-				(void) chown(line, getuid(), ttygid);
-				(void) chmod(line, S_IRUSR|S_IWUSR|S_IWGRP);
-				(void) revoke(line);
-				if ((slave = open(line, O_RDWR, 0)) != -1) {
-					*amaster = master;
-					*aslave = slave;
-					if (name)
-						strcpy(name, line);
-					if (termp)
-						(void) tcsetattr(slave,
-							TCSAFLUSH, termp);
-					if (winp)
-						(void) ioctl(slave, TIOCSWINSZ,
-							(char *)winp);
-					return (0);
-				}
-				(void) close(master);
-			}
-		}
+	const char *slavename;
+	int master, slave;
+
+	master = posix_openpt(O_RDWR);
+	if (master == -1)
+		return (-1);
+
+	if (grantpt(master) == -1) {
+		close(master);
+		return (-1);
+	}
+
+	slavename = ptsname(master);
+	if (slavename == NULL) {
+		close(master);
+		return (-1);
+	}
+
+	if (revoke(slavename) == -1) {
+		close(master);
+		return (-1);
 	}
-	errno = ENOENT;	/* out of ptys */
-	return (-1);
+
+	slave = open(slavename, O_RDWR);
+	if (slave == -1) {
+		close(master);
+		return (-1);
+	}
+
+	if (unlockpt(master) == -1) {
+		close(master);
+		close(slave);
+		return (-1);
+	}
+
+	*amaster = master;
+	*aslave = slave;
+
+	if (name)
+		strcpy(name, slavename);
+	if (termp)
+		tcsetattr(slave, TCSAFLUSH, termp);
+	if (winp)
+		ioctl(slave, TIOCSWINSZ, (char *)winp);
+
+	return (0);
 }
 
 int
